package com.gps.gate;

import com.gps.common.model.Command;
import com.gps.gate.database.ActiveDevice;

import java.util.*;

public abstract class BaseProtocol implements Protocol {

    private final String name;
    private final Set<String> supportedDataCommands = new HashSet<>();
    private final List<TrackerServer> serverList = new LinkedList<>();

    public static String nameFromClass(Class<?> clazz) {
        String className = clazz.getSimpleName();
        return className.substring(0, className.length() - 8).toLowerCase();
    }

    public BaseProtocol() {
        name = nameFromClass(getClass());
    }

    @Override
    public String getName() {
        return name;
    }

    protected void addServer(TrackerServer server) {
        serverList.add(server);
    }

    @Override
    public Collection<TrackerServer> getServerList() {
        return serverList;
    }

    public void setSupportedDataCommands(String... commands) {
        supportedDataCommands.addAll(Arrays.asList(commands));
    }
    @Override
    public Collection<String> getSupportedDataCommands() {
        Set<String> commands = new HashSet<>(supportedDataCommands);
        commands.add(Command.TYPE_CUSTOM);
        return commands;
    }
    @Override
    public void sendDataCommand(ActiveDevice activeDevice, Command command) {
        if (supportedDataCommands.contains(command.getType())) {
            activeDevice.write(command);
        } else {
            throw new RuntimeException("Command " + command.getType() + " is not supported in protocol " + getName());
        }
    }

}
